<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="不知道警告啥，好像是必须选三级标签吧" type="warning" left show-icon :closable="false"></el-alert>
      <el-row class="wwm">
        <el-col>
          <!-- api 1.6.1 -->
          选择商品分类:
          <el-cascader
            expandTrigger="hover"
            v-model="cateSelected"
            :options="cateList"
            :props="cascaderProps"
            @change="cascaderChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- v-model是激活的tab标签name -->
      <el-tabs v-model="tabName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" plain :disabled="isDisabled" @click="addDialogVisible=true">添加参数</el-button>
          <el-table :data="manyTableData" style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  style="margin-right:5px"
                  closable
                  @close="removeTag(scope.row,i)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputTagConfirm(scope.row)"
                  @blur="handleInputTagConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="分类参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" content="修改" icon="el-icon-edit">修改</el-button>
                <el-button
                  type="danger"
                  content="删除"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" plain :disabled="isDisabled" @click="addDialogVisible=true">添加属性</el-button>
          <el-table :data="onlyTableData" style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  style="margin-right:5px"
                  closable
                  @close="removeTag(scope.row,i)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputTagConfirm(scope.row)"
                  @blur="handleInputTagConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="分类参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" content="修改" icon="el-icon-edit">修改</el-button>
                <el-button
                  type="danger"
                  content="删除"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="'添加'+dialogShowTitle"
      @close="addDialogClose"
      :visible.sync="addDialogVisible"
    >
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="dialogShowTitle+':'" prop="addInfo">
          <!-- prop具体校验规则 -->
          <el-input v-model="addForm.addInfo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClose()">取 消</el-button>
        <el-button type="primary" @click="addInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类的List
      cateList: [],
      //选择的值 三级标签数组长度为3  二级标签数组长度为2
      cateSelected: [],
      //三级规则
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },

      //绑定的tab名
      tabName: 'many',

      //动态参数数据
      manyTableData: [],
      //静态参数数据
      onlyTableData: [],

      //对话框显示
      addDialogVisible: false,
      //添加
      addForm: {
        addInfo: ''
      },
      //form表单验证规则
      addFormRules: {
        addInfo: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
      // //newtag input框控制显示
      // inputVisible:false,
      //newtag input填入的值
      // inputTagValue: ''
    }
  },
  created() {
    this.getCascaderSelector()
  },
  //计算属性，监听
  computed: {
    //添加按钮
    isDisabled() {
      if (this.cateSelected.length < 3) {
        return true
      } else {
        return false
      }
    },

    //当前选中的三级id
    selectedId() {
      if (this.cateSelected.length < 3) {
        return null
      } else {
        return this.cateSelected[2]
      }
    },
    //为dialog分别加上两种显示方式
    dialogShowTitle() {
      if (this.tabName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    }
  },
  methods: {
    // 1.6.1
    async getCascaderSelector() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status != 200) {
        return this.$message.error('错误！')
      }
      this.$message.success('获取级联选择！')
      this.cateList = res.data
    },
    //级联框被选定时 获取表格参数
    async cascaderChange() {
      this.getDataTable()
      //   if (this.cateSelected.length < 3) {
      //     this.cateSelected = []
      //     return this.$message.error('不能选择三级标签以下的')
      //   }

      //   const {data:res}=await this.$http.get(`categories/${this.selectedId}/attributes`,{
      //       params:{"sel":this.tabName}
      //   })
      //   if(res.meta.status!=200){
      //        return this.$message.error('获取失败！')
      //   }
      //   this.$message.success('获取成功！')
      // //   console.log(res);
    },
    //tab鼠标点击事件
    handleTabClick() {
      this.getDataTable()
    },
    // 属性添加

    // 抽取一个方法  当级联选择选择时 或 tab标签选择时 执行 渲染table表
    async getDataTable() {
      if (this.cateSelected.length < 3) {
        this.cateSelected = []
        this.manyTableData=[]
        this.onlyTableData=[]
        return
        // return this.$message.error('不能选择三级标签以下的')
      }

      const { data: res } = await this.$http.get(
        `categories/${this.selectedId}/attributes`,
        {
          params: { sel: this.tabName }
        }
      )
      //拆解为标签
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputTagValue = ''
      })
      if (res.meta.status != 200) {
        return this.$message.error('获取失败！')
      }
      this.$message.success('获取成功！')
      if (this.tabName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },
    //对话框关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
      this.addDialogVisible = false
    },
    //对话框确定事件
    addInfo() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        console.log(this.selectedId, this.addForm.addInfo, this.tabName)

        const { data: res } = await this.$http.post(
          `/categories/${this.selectedId}/attributes`,
          {
            attr_name: this.addForm.addInfo,
            attr_sel: this.tabName
          }
        )
        console.log(res)

        if (res.meta.status != 201) {
          return this.$message.error('创建失败')
        }
        this.$message.success('创建成功')
        this.addDialogVisible = false
        this.getDataTable()
      })
    },
    //删除参数1.7.3
    async removeParams(row) {
      const resultConfirm = await this.$confirm(
        '此操作将永久删除该条目, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (!resultConfirm) {
        return this.$message.error('您取消了删除操作')
      }

      const { data: res } = await this.$http.delete(
        `categories/${this.selectedId}/attributes/${row.attr_id}`
      )

      if (res.meta.status != 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功')
      this.getDataTable()
    },
    //newtag失去焦点或者回车时触发 1.7.5
    async handleInputTagConfirm(row) {
      if (!row.inputTagValue.trim()) {
        row.inputTagValue = ''
        row.inputVisible = false
      }
            //如果后端更新成功在前端页面上显示tag
      row.attr_vals.push(row.inputTagValue)
      this.setTagValue(row)
    },
    //点击new tag触发的事件
    showInput(row) {
      row.inputVisible = true
      //$nextTick是要元素被渲染后再显示
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //将tag删除
    removeTag(row,i){
        row.attr_vals.splice(i,1)
        this.setTagValue(row)
    },


    //tag删除添加通用方法
    async setTagValue(row) {
      //将tag列表传入后端
      const { data: res } = await this.$http.put(
        `categories/${this.selectedId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('更改tag成功')
      row.inputTagValue = ''
      row.inputVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.wwm {
  margin: 20px 0 0 0;
}
.input-new-tag {
  width: 140px;
}
</style>